const app = getApp();
const util = require('../../utils/util.js')
const {toast} = require("../../utils/tool");
Page({
    /**
     * 页面的初始数据
     */
    data: {
        service: false,
        lockHexId: '',
        lockId: '',
        _isNotifyReturn: false,
        lock_brand: true, //锁的类型标记判断是不是231型号的锁
        maxFailNums: 3,
        delayTime: 300,
        _failNums: 0,
        page: 1,
        list: [],
        is_ajax: false,
        is_over: false,
        status: 0,
        blueYaCode: '',
        // 门锁蓝牙的id
        deviceId: '',
        // 服务uuid
        servicesUUID: '',
        // 开启notify的characteristicId
        notifyCharacteristicId: '',
        // 开启write的characteristicId
        writeCharacteristicId: '',
        //
        characteristics: []
    },
    // 开大门
    async openBig() {
        console.log(wx.getStorageSync('firststore'))
        let store = wx.getStorageSync('firststore')
        app.ajax({
            url: '/api/frontdoor/openfrontdoor', data: {
                store_id: store[0].id
            }, success: res => {
                wx.showToast({
                    title: res.msg,
                    icon: 'none'
                })
            }
        })
    },
    async openDoorBig(e) {
        let self = this
        //传入1是开大门传入2是开房间门
        self.getBlueYaCode(1, e.currentTarget.dataset.id);
        // 获取需要写入的数据
        setTimeout(() => {
            if (this.data.blueYaCode) {
                // 初始化蓝牙判断是否开启蓝牙
                wx.openBluetoothAdapter({
                    success(res) {
                        // 执行搜索蓝牙
                        setTimeout(() => {
                                self.findBlue();
                            },
                            // 安卓开启蓝牙后，需要300ms延迟
                            self.isModel() == 'android' ? this.data.delayTime : 0
                        )
                    },
                    fail(err) {
                        wx.showToast({
                            title: '请开启蓝牙,部分安卓手机需要开启定位服务',
                            icon: 'none',
                            duration: 800
                        })
                        return
                    }
                })
            }
        }, 1000)

    },
    getBlueYaCode(type, orderId) {
        let self = this
        app.ajax({
            url: '/api/lock/open',
            data: {
                type: type,
                orderId: orderId
            },
            success(res) {
                self.setData({
                    lockId: res.data.lockId,
                    blueYaCode: res.data.key
                })
            }
        })
    },
    close(e) {
        wx.showModal({
            title: '您确定提前结束吗?',
            success: ({cancel}) => {
                if (cancel) return
                let self = this;
                const id = e.currentTarget.dataset.id
                app.ajax({
                    url: '/api/user/earlyClose',
                    data: {
                        order_id: id.toString().trim()
                    },
                    success(res) {
                        const {msg, code} = res
                        toast({title: msg})
                        if (code === 1) {
                            self.getList(1)
                        }
                    }
                })
            }
        })

    },
    openLockHandler(id) {
        app.ajax({
            url: '/api/lock/open',
            data: {
                type: 2,
                orderId: id
            },
            success(res) {
                const {code, data, msg} = res
                toast({title: msg})
                // self.setData({
                //     lockId: res.data.lockId,
                //     blueYaCode: res.data.key
                // })
            }
        })
    },
    cancelOrder(e) {
        wx.showModal({
            title: '您确认取消订单吗?',
            success: res => {
                if (res.cancel) return
                const {id} = e.currentTarget.dataset
                app.ajax({
                    url: "/api/user/canalOrder",
                    data: {order_id: id},
                    success: resp => {
                        const {msg} = resp
                        toast({title: msg})
                        this.getList(1);
                    }
                })
            }
        })

    },
    // 开 房间 门
    async openDoorSmall(e) {
        const {status, id} = e.currentTarget.dataset
        if (status == 31) return this.openLockHandler(id);
        wx.showModal({
            title: '提前开启',
            content: '是否提前开启包间？结束时间也将提前结束',
            success: (res) => {
                if (res.cancel) return
                this.openLockHandler(id)
                return;
                app.ajax({
                    url: "/api/user/earlyOpening",
                    data: {order_id: id},
                    success: (resp) => {
                        const {code, msg} = resp
                        if (code !== 1) return toast({title: msg})

                    }
                })
            }
        })
    },
    // 开始搜索蓝牙
    findBlue() {
        let self = this
        wx.startBluetoothDevicesDiscovery({
            allowDuplicatesKey: false,
            interval: 0,
            success(res) {
                setTimeout(() => {
                    // 获取蓝牙列表
                    self.getBlueYaList();
                }, 2000)
                wx.showLoading({
                    title: '正在搜索设备',
                })
            },
            fail(res) {
                this.bluetoothFailAgain()
            },
        })
    },
    // 转换
    ab2hex(buffer) {
        var hexArr = Array.prototype.map.call(new Uint8Array(buffer), function (bit) {
            return ('00' + bit.toString(16)).slice(-2);
        });
        return hexArr.join('');
    },
    // 获取蓝牙列表
    getBlueYaList() {
        let self = this
        wx.getBluetoothDevices({
            success: function (res) {
                wx.hideLoading();
                self.findDevice(res.devices)
                // console.log(res, "蓝牙列表");
                // for (var i = 0; i < res.devices.length; i++) {
                // 	if (res.devices[i].name == "BLE_HUOHELOCK") {
                // 		console.log(res.devices[i], "目标数据");
                // 		self.setData({
                // 			deviceId: res.devices[i].deviceId
                // 		})
                // 		// 链接蓝牙
                // 		self.connectBlueYa(self.data.deviceId)
                // 	}
                // }
            }
        })
    },
    /*连接蓝牙 */
    connectBlueYa(deviceId) {
        let self = this
        wx.createBLEConnection({
            deviceId: deviceId,
            success(res) {
                console.log(res, "连接状态");
                if (res.errCode == 0) {
                    wx.showToast({
                        title: '蓝牙连接成功',
                        icon: 'none',
                        duration: 800
                    })
                    // 获取服务
                    self.getBLEDeviceServices(deviceId)
                } else {
                    wx.showToast({
                        title: '蓝牙连接失败',
                        icon: 'none',
                        duration: 800
                    })
                }
                // 关闭搜索功能
                wx.stopBluetoothDevicesDiscovery({
                    success: function (res) {
                        console.log("成功关闭蓝牙搜索功能");
                    }
                })
            }
        })
    },
    // 获取服务UUID
    getBLEDeviceServices(deviceId) {
        let that = this
        wx.getBLEDeviceServices({
            deviceId,
            success: (res) => {
                console.log('getBLEDeviceServices', res)
                for (var i = 0; i < res.services.length; i++) {
                    if (res.services[i].uuid == "0000FFF0-0000-1000-8000-00805F9B34FB") {
                        console.log("服务已找到");
                        console.log(res.services[i].uuid);
                        that.setData({
                            servicesUUID: res.services[i].uuid
                        })
                    }
                }
                // 获取连接设备具有读写功能服务的所有特征值
                that.getBLEDeviceCharacteristics();
            },
            fail: (res) => {
                console.log('getBLEDeviceServices fail', res);
                that.bluetoothFailAgain();
            }
        })
    },
    // 获取连接设备具有读写功能服务的所有特征值
    getBLEDeviceCharacteristics() {
        var that = this;
        wx.getBLEDeviceCharacteristics({
            deviceId: that.data.deviceId,
            serviceId: that.data.servicesUUID,
            success: (res) => {
                console.log(res.characteristics, "数据");
                //获取特征值
                for (var i = 0; i < res.characteristics.length; i++) {
                    //把特征值id输出到控制台
                    if (res.characteristics[i].properties.notify) {
                        console.log("开启notify的characteristicId:" + res.characteristics[i].uuid);
                        that.setData({
                            notifyCharacteristicId: res.characteristics[i].uuid
                        })
                    }
                    //res.characteristics[i].properties.write
                    if (res.characteristics[i].properties.write) {
                        console.log("开启write的characteristicId:" + res.characteristics[i].uuid);
                        that.setData({
                            writeCharacteristicId: res.characteristics[i].uuid
                        })
                    }
                    if (res.characteristics[i].properties.read) {
                        console.log("开启read的characteristicId:" + res.characteristics[i].uuid);
                    }
                }
                console.log(that.data.writeCharacteristicId, "写入特征值ID");
                console.log(that.data.notifyCharacteristicId, "开启notify的ID");
                // 把数据写道data中
                that.setData({
                    characteristics: res.characteristics
                })
                // 启用蓝牙特征值变化
                that.notifyBLECharacteristicValueChange();
            },
            fail: (res) => {
                console.log("失败了")
                this.bluetoothFailAgain();
            },
            complete: (res) => {

            },
        })
    },
    onBLENoticeCallBack() {
        wx.showToast({
            title: 'onBLECharacteristicValueChange 回调',
            icon: 'none',
            duration: 800
        })
    },
    closeBLEConnection() {
        if (this.data.deviceId) {
            wx.closeBLEConnection({
                deviceId: this.data.deviceId,
                success: () => {
                    this.log('成功断开连接')
                },
            })
        }
    },
    stopBluetoothDevicesDiscovery() {
        wx.stopBluetoothDevicesDiscovery({
            complete: () => {
                this._discoveryStarted = false
            },
        })
    },
    clear() {
        this._failNums = 0;
        /* 设置traceId */
    },
    openLock() {
        this._scanTimer = setTimeout(() => {
            // this.blueToothErrorCode = ErrorCode.scanTimeout
            this.bluetoothFailAgain()
        }, 8000)
        let self = this
        wx.openBluetoothAdapter({
            success(res) {
                // 执行搜索蓝牙
                self.findBlue()
            },
            fail(err) {
                wx.showToast({
                    title: '请开启蓝牙,部分安卓手机需要开启定位服务',
                    icon: 'none',
                    duration: 800
                })
                return
            }
        })
    },
    // 关闭蓝牙
    bluetoothFailAgain() {
        this.stopBluetoothDevicesDiscovery()
        this.closeBLEConnection()
        // 关闭蓝牙
        this.closeBluetoothAdapter(() => {
            this._failNums += 1
            console.log('失败次数:', this._failNums)
            if (this._failNums === this.maxFailNums) {
                console.log(`到失败次数上限:`, this.maxFailNums)
            } else if (this._failNums < this.maxFailNums) {
                setTimeout(() => {
                    console.log('失败后重新开始')
                    // 失败后的开始
                    this.openLock(this.device)
                }, 200)
            }
        })
    },
    // 监听
    notifyBLECharacteristicValueChange() {
        function buf2hex(buffer) {
            return Array.prototype.map.call(new Uint8Array(buffer), (x) => ('00' + x.toString(16)).slice(-2))
                .join('')
        }

        function stringToHex(str) {
            const arr = str.split('.')
            return arr
                .map((item) => {
                    let num = Number(item).toString(16)
                    if (num.length < 2) {
                        num = '0' + num
                    }
                    return num
                })
                .join('')
        }

        // 监听通知
        var that = this;
        wx.onBLECharacteristicValueChange((res) => {
            console.log(res, '监听到返回的数据');
            wx.showToast({
                title: '监听到返回的数据',
                icon: 'none',
                duration: 800
            })
            that._isNotifyReturn = true;
            const hex = buf2hex(res.value)
            // const verify = `${stringToHex(device.lockId.split('.').reverse().join('.'))}0900005001`
            // const verifyCode = `${stringToHex(device.lockId.split('.').reverse().join('.'))}0900005000`
            let find = hex.indexOf('1a0794aa') > -1;
            if (find && (that.data.lock_brand)) {
                wx.showToast({
                    title: '开锁成功',
                    icon: 'none',
                    duration: 800
                })
                // let key = data.data.data
                that.writeBLECharacteristicValueDelete(key)
                return
            }
        })

        if (this.data.lock_brand) {
            // var that = this;
            wx.notifyBLECharacteristicValueChange({
                deviceId: that.data.deviceId,
                serviceId: that.data.servicesUUID,
                characteristicId: that.data.notifyCharacteristicId,
                state: true,
                success: (res) => {
                    // console.log('通知打开成功 231 锁,' + JSON.stringify(res));
                },
                fail: (res) => {
                    // console.log('通知打开失败231 锁,' + JSON.stringify(res));
                }
            })
        }
        wx.notifyBLECharacteristicValueChange({
            deviceId: that.data.deviceId,
            serviceId: that.data.servicesUUID,
            characteristicId: that.data.notifyCharacteristicId,
            state: true,
            success: (res) => {
                // android 打开通知成功后等待200ms再写入数据，iOS不用等待
                if (that.isModel() == 'android') {
                    setTimeout(() => {
                        that._isNotifyReturn = false
                        that.writeBLECharacteristicValue()
                    }, that.delayTime)

                } else {
                    wx.showToast({
                        title: '苹果设备',
                        icon: 'none',
                        duration: 800
                    })
                    that._isNotifyReturn = false
                    that.writeBLECharacteristicValue();
                }
            },
            fail: (res) => {
                console.log('通知打开失败', 4004)
                this.bluetoothFailAgain()
            },
        })
    },
    writeBLECharacteristicValueDelete(key) {
        // 火河A231门锁需要特殊处理
        let list = []
        while (key != null && key.length) {
            let str = key.substring(0, 2)
            let num = parseInt(str, 16)
            list.push(num)
            key = key.substring(2);
        }
        let arrayBuffer = new Uint8Array(list).buffer;
        console.log(arrayBuffer, 'arrayBuffer')
        // 向门锁写入删除数据
        wx.writeBLECharacteristicValue({
            deviceId: this.device.deviceId,
            serviceId: this.device.servicesUUID,
            characteristicId: this.data.writeCharacteristicId, //'0000FFF4-0000-1000-8000-00805F9B34FB',
            value: arrayBuffer,
            success: (res) => {
                console.log(res, 'res')
                // this.closeBluetoothAdapter()
            },
            fail: (res) => {
                console.log(res, 'res')
            },
        })
    },
    //字符串转arrbuffer
    stringToHexBuffer(value) {
        var typedArray = new Uint8Array(value.match(/[\da-f]{2}/gi).map(function (h) {
            console.log('转数据1');
            return parseInt(h, 16);
        }))
        console.log('转数据2');
        return typedArray.buffer;
    },
    findDevice(devices) {
        let self = this

        function stringToHex(str) {
            const arr = str.split('.')
            return arr
                .map((item) => {
                    let num = Number(item).toString(16)
                    if (num.length < 2) {
                        num = '0' + num
                    }
                    return num
                })
                .join('')
        }

        devices.forEach((device) => {
            // 蓝牙设备advertisData属性转换出来的数据
            var we = self.ab2hex(device.advertisData);
            // 锁设备的编号转换出来的数据
            var lockHexId = stringToHex(self.data.lockId);
            console.log(lockHexId === we, "判断");
            // 蓝牙设备advertisData属性转换出来的数据和锁设备的编号转换出来的数据相等则开门
            if (device.advertisData && self.ab2hex(device.advertisData) === lockHexId) {
                self.setData({
                    deviceId: device.deviceId
                })
                self.connectBlueYa(device.deviceId);
            }
        })
    },
    // 判断机型
    isModel() {
        let res = wx.getSystemInfoSync();
        console.log(res.platform == 'ios', "苹果");
        console.log(res.platform == 'android', "安卓");
        console.log(res.platform == 'devtools', "模拟器");
        return res.res
    },
    // 写入数据
    writeBLECharacteristicValue() {
        var that = this;
        let temp = `BABEC0DE` + that.data.blueYaCode;
        const secretNum = temp.toLocaleLowerCase();
        let buffer = '';
        console.log('往锁写入的数据：', secretNum)
        let step = 0
        let count = 0
        let step2 = 0

        function writeBLE() {
            console.log('次数' + count);
            buffer = that.stringToHexBuffer(secretNum)
            wx.writeBLECharacteristicValue({
                deviceId: that.data.deviceId,
                serviceId: that.data.servicesUUID,
                characteristicId: that.data.writeCharacteristicId,
                value: buffer,
                success: () => {
                    if (that.data.lock_brand) {
                        wx.showToast({
                            title: '写入数据完成',
                            icon: 'none',
                            duration: 800
                        })
                        return
                    }
                    console.log(`锁写入数据剩余：${secretNum.length - step2}`)
                    if (step2 != secretNum.length && !that._isNotifyReturn) {
                        step += 32
                        writeBLE();
                    } else {
                        // console.log('写入完成')
                        wx.showToast({
                            title: '写入数据完成',
                            icon: 'none',
                            duration: 800
                        })
                    }
                },
                fail: (res) => {
                    count++
                    // 写入失败时，重试3次，一次完整的写入，失败3次以上，算这次开锁失败
                    if (count > 2 && !that._isNotifyReturn) {
                        this.bluetoothFailAgain()
                    } else if (!that._isNotifyReturn) {
                        writeBLE()
                    }
                    console.log('写入数据失败', res)
                },
            })
        }

        writeBLE();
    },

    unsettled: function (e) {
        var id = e.currentTarget.dataset.id;
        wx.navigateTo({
            url: '/pages/unsettled/unsettled?order_id=' + id
        })
    },
    opening_code: function (e) {
        var id = e.currentTarget.dataset.id;
        wx.navigateTo({
            url: '/pages/opening_code/opening_code?order_id=' + id
        })
    },
    used: function () {
        wx.navigateTo({
            url: '/pages/used/used',
        })
    },
    expired: function () {
        wx.navigateTo({
            url: '/pages/expired/expired',
        })
    },
    setStatus: function (e) {
        var status = e.currentTarget.dataset.status;
        if (this.data.status != status) {
            this.setData({
                status: status
            });
            this.getList(1);
        }
    },
    getList: function (reset) {
        if (reset) {
            this.setData({
                page: 1,
                list: [],
                is_ajax: false,
                is_over: false
            });
        }
        // if (this.data.is_ajax || this.data.is_over) return false;
        // this.setData({
        //     is_ajax: true
        // });
        var page = this.data.page,
            status = this.data.status,
            list = this.data.list,
            is_ajax = true,
            is_over = false;
        app.ajax({
            url: '/api/user/orderList',
            data: {
                status: status,
                page: page
            },
            success: res => {
                const statusEnum = {
                    '10': '待支付',
                    '20': '已取消',
                    '30': '已预约',
                    '31': '进行中',
                    '29': '已转让',
                    '32': '已完成',
                    '40': '待退款',
                    '41': '已退款',
                    '42': '已退款'
                }
                if (!res.data) {
                    res.data = []
                }
                if (res.code == 1) {
                    page++;
                    list = list.concat(res.data.map(item => {
                        item.statusText = statusEnum[item.status]
                        return item
                    }));
                    // let now = parseInt(Date.now() / 1000);
                    // for (let item of list) {
                    // console.log(list[i],'item')
                    // if (list[i].status == 10) {
                    //     list[i].gopay_time = parseInt((list[i].create_time + 180 - now) / 60);
                    //     if (list[i].gopay_time < 0) list[i].gopay_time = 0;
                    // }
                    // }
                } else {
                    is_over = true;
                }
                is_ajax = false;
                this.setData({
                    page: page,
                    list: list,
                    is_ajax: is_ajax,
                    is_over: is_over
                });
            }
        })
    },
    onShow: function () {
        this.getList(1);
    },
    onReachBottom: function () {
        this.getList();
    },
    onShareAppMessage: function (res) {
        const {userData} = app.globalData
        const {id: userId} = userData
        const {dataset: {id}} = res.target
        return {
            title: '亲 赠送给你一个茶室包间请 前去消费',
            path: `/pages/opening_code/opening_code?type=1&order_id=${id}&id=${userId}`, //这里是被分享的人点击进来之后的页面
        }
    },

})
